package xginxgodb

import (
	"encoding/json"
	"strings"

	"gitee.com/xiaoyutab/xgotool/xgin"
	"gitee.com/xiaoyutab/xgotool/xgodb"
	"gitee.com/xiaoyutab/xgotool/xgodb/xgodbconfig"
	"gitee.com/xiaoyutab/xgotool/xstring"
	"github.com/gin-gonic/gin"
)

// POST接收其他端推送过来的配置项变更请求
//
//	POST	sync.configure.xgin
func syncPost(c *gin.Context) *xgin.Response {
	type temp_struct struct {
		Dates string `json:"dates" form:"dates" xml:"dates"` // datas参数
		Urls  string `json:"urls" form:"urls" xml:"urls"`    // urls参数
	}
	temp := temp_struct{}
	if err := xgin.Bind(c, &temp); err != nil {
		return xgin.Resp().Error(err)
	}
	// 正式变量赋值
	// 请使用param进行参数验证、变量效验等操作
	param := temp
	// 获取请求值中的url，用于获取AES密钥解析
	aes_key := strings.Split(xgodb.GetString("FRAM_SYNC_URL_AES"), ",")
	aes_url := strings.Split(xgodb.GetString("FRAM_SYNC_URL"), ",")
	if len(aes_key) != len(aes_url) {
		return xgin.Resp().ErrorString("系统项内同步配置项获取失败，请稍后在试")
	}
	// 获取对应的aes_key
	aes := ""
	for i := 0; i < len(aes_url); i++ {
		if aes_url[i] == param.Urls {
			aes = aes_key[i]
			break
		}
	}
	if aes == "" {
		return xgin.Resp().ErrorString("域名对应的AES密钥查找失败，请线下同步后再次尝试")
	}
	// 针对body进行base64解码
	base64 := xstring.UnBase64Byte(param.Dates)
	if len(base64) == 0 {
		return xgin.Resp().ErrorString("Base64解码失败，请调整后再试")
	}
	// AES解密
	c_j, err := xstring.UnAes(base64, []byte(aes))
	if err != nil {
		return xgin.Resp().Error(err)
	}
	// 将解密后的字符串进行json反串行化
	conf := xgodbconfig.Configure{}
	if err := json.Unmarshal(c_j, &conf); err != nil {
		return xgin.Resp().Error(err)
	}
	// 转换完成的配置项进行入库存储
	switch conf.Types {
	case "string":
		err = xgodb.SetString(conf.NameKey, conf.ValueString)
	case "int":
		err = xgodb.SetInt(conf.NameKey, conf.ValueInt)
	case "float":
		err = xgodb.SetFloat(conf.NameKey, conf.ValueFloat)
	case "bool":
		err = xgodb.SetBool(conf.NameKey, conf.ValueBool == 1)
	case "select":
		err = xgodb.SetSelect(conf.NameKey, conf.ValueString)
	case "text":
		err = xgodb.SetText(conf.NameKey, conf.ValueString)
	case "longtext":
		err = xgodb.SetLongText(conf.NameKey, conf.ValueString)
	}
	if err != nil {
		return xgin.Resp().Error(err)
	}
	return xgin.Resp().SuccessEmpty()
}
